let dao = require('../database/dao'),
  logger = require('../helper/logger'),
  tagLogger = new logger.TagLogger('ORDER_MODEL'),
  errCode = require('../../conf/errorCode'),
  util = require('../helper/util');

exports.upsertUser = function(accountName, callback) {
  let str = `INSERT INTO user(accountName) 
              VALUES(?) 
              ON DUPLICATE KEY UPDATE loginAt = CURRENT_TIMESTAMP`;
  dao.all(str, [accountName], (err, rslt) => {
    if (err == null) {
      callback(null, {userId: rslt.insertId});
    } else {
      tagLogger.error(
        `upserUser, err[${JSON.stringify(err)}], accountName[${accountName}]`,
      );
      callback({errNo: errCode.UPSERT_USER_ERROR}, null);
    }
  });
};

exports.checkAuth = function(accountName, passWd, callback) {
  let str = `SELECT id,accountName,status,role FROM user WHERE accountName = ? AND passWd = ?`;
  dao.all(str, [accountName, passWd], function(err, _rel) {
    if (err == null && _rel.length > 0) {
      callback(null, _rel[0]);
    } else {
      tagLogger.info(`checkAuth fail. accountName[${accountName}], 
                            userObj[${JSON.stringify(
                              _rel,
                            )}], error[${JSON.stringify(err)}]`);
      callback({errNo: errCode.PASSWORD_CHECK_ERROR}, null);
    }
  });
};
